<template>
  <div class="product-detail">
    <el-container class="full-height">
      <el-header class="header">
        <div class="header-content">
          <div class="header-left">
            <el-button @click="$router.go(-1)" icon="ArrowLeft">返回</el-button>
            <h1>{{ product?.name || '产品详情' }}</h1>
          </div>
          <div class="user-info">
            <span class="username">欢迎，{{ userInfo?.username }}</span>
            <el-button type="danger" size="small" @click="handleLogout">
              <el-icon><SwitchButton /></el-icon>
              登出
            </el-button>
          </div>
        </div>
      </el-header>
      
      <el-main class="main-content">
        <el-tabs v-model="activeTab" type="card" class="full-height-tabs">
          <!-- 固件列表 TAB -->
          <el-tab-pane label="固件列表" name="firmware">
            <div class="tab-content">
              <el-card class="content-card">
                <template #header>
                  <div class="tab-header">
                    <h3>固件列表</h3>
                    <el-button type="primary" @click="showFirmwareDialog = true">
                      <el-icon><Plus /></el-icon>
                      新增固件
                    </el-button>
                  </div>
                </template>
                
                <el-table :data="firmwares" v-loading="firmwareLoading" style="width: 100%" size="small">
                  <el-table-column prop="version" label="版本号" />
                  <el-table-column prop="description" label="描述" />
                  <el-table-column prop="file_size" label="文件大小">
                    <template #default="scope">
                      {{ formatFileSize(scope.row.file_size) }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="release_time" label="发布时间">
                    <template #default="scope">
                      {{ formatDate(scope.row.release_time) }}
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="200">
                    <template #default="scope">
                      <el-button size="small" @click="downloadFirmware(scope.row)">
                        下载
                      </el-button>
                      <el-button size="small" type="danger" @click="deleteFirmware(scope.row)">
                        删除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-card>
            </div>
          </el-tab-pane>

          <!-- 任务列表 TAB -->
          <el-tab-pane label="任务列表" name="task">
            <div class="tab-content">
              <el-card class="content-card">
                <template #header>
                  <div class="tab-header">
                    <h3>任务列表</h3>
                    <el-button type="primary" @click="showTaskDialog = true">
                      <el-icon><Plus /></el-icon>
                      新增任务
                    </el-button>
                  </div>
                </template>
                
                <el-table :data="tasks" v-loading="taskLoading" style="width: 100%" size="small">
                  <el-table-column prop="name" label="任务名称" />
                  <el-table-column prop="task_type" label="任务类型" />
                  <el-table-column prop="sn" label="设备SN">
                    <template #default="scope">
                      {{ scope.row.sn || '所有设备' }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="version" label="目标版本" />
                  <el-table-column prop="status" label="状态">
                    <template #default="scope">
                      <el-tag :type="getStatusType(scope.row.status)">
                        {{ scope.row.status }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column prop="effective_time" label="生效时间">
                    <template #default="scope">
                      {{ formatDate(scope.row.effective_time) }}
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="200">
                    <template #default="scope">
                      <el-button size="small" @click="editTask(scope.row)">
                        编辑
                      </el-button>
                      <el-button size="small" type="danger" @click="deleteTask(scope.row)">
                        删除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-card>
            </div>
          </el-tab-pane>

          <!-- 升级记录 TAB -->
          <el-tab-pane label="升级记录" name="upgrade">
            <div class="tab-content">
              <el-card class="content-card">
                <template #header>
                  <div class="tab-header">
                    <h3>升级记录</h3>
                    <el-button type="primary" :icon="Plus" @click="loadUpgradeRecords" :loading="upgradeLoading">
                      刷新
                    </el-button>
                  </div>
                </template>
                
                <el-table :data="upgradeRecords" v-loading="upgradeLoading" style="width: 100%" size="small">
                  <el-table-column prop="sn" label="设备SN" />
                  <el-table-column prop="version" label="版本号" />
                  <el-table-column prop="status" label="状态">
                    <template #default="scope">
                      <el-tag :type="getUpgradeStatusType(scope.row.status)">
                        {{ scope.row.status }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column prop="upgrade_time" label="升级时间">
                    <template #default="scope">
                      {{ formatDate(scope.row.upgrade_time) }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="message" label="消息" />
                </el-table>
              </el-card>
            </div>
          </el-tab-pane>

          <!-- 终端列表 TAB -->
          <el-tab-pane label="终端列表" name="device">
            <div class="tab-content">
              <el-card class="content-card">
                <template #header>
                  <div class="tab-header">
                    <h3>终端列表</h3>
                    <el-button type="primary" @click="showDeviceDialog = true">
                      <el-icon><Plus /></el-icon>
                      新增设备
                    </el-button>
                  </div>
                </template>
                <el-table :data="devices" v-loading="deviceLoading" style="width: 100%" size="small">
                  <el-table-column prop="sn" label="设备SN" />
                  <el-table-column prop="current_version" label="当前版本" />
                  <el-table-column prop="status" label="状态">
                    <template #default="scope">
                      <el-tag :type="scope.row.status === 'online' ? 'success' : 'danger'">
                        {{ scope.row.status }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column prop="last_check_time" label="最后检查时间">
                    <template #default="scope">
                      {{ formatDate(scope.row.last_check_time) }}
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="200">
                    <template #default="scope">
                      <el-button size="small" @click="editDevice(scope.row)">
                        编辑
                      </el-button>
                      <el-button size="small" type="danger" @click="deleteDevice(scope.row)">
                        删除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-card>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-main>
    </el-container>

    <!-- 新增固件对话框 -->
    <el-dialog v-model="showFirmwareDialog" title="新增固件" width="600px">
      <el-form :model="firmwareForm" :rules="firmwareRules" ref="firmwareFormRef" label-width="120px">
        <el-form-item label="版本号" prop="version">
          <el-input v-model="firmwareForm.version" placeholder="请输入版本号" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="firmwareForm.description" type="textarea" placeholder="请输入描述" />
        </el-form-item>
        <el-form-item label="固件文件" prop="file">
          <el-upload
            ref="uploadRef"
            :auto-upload="false"
            :on-change="handleFileChange"
            :file-list="fileList"
            accept=".bin,.zip,.tar.gz,.apk"
          >
            <el-button type="primary">选择文件</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showFirmwareDialog = false">取消</el-button>
          <el-button type="primary" @click="createFirmware" :loading="creatingFirmware">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 新增任务对话框 -->
    <el-dialog v-model="showTaskDialog" title="新增任务" width="500px">
      <el-form :model="taskForm" :rules="taskRules" ref="taskFormRef" label-width="120px">
        <el-form-item label="任务名称" prop="name">
          <el-input v-model="taskForm.name" placeholder="请输入任务名称" />
        </el-form-item>
        <el-form-item label="任务类型" prop="task_type">
          <el-select v-model="taskForm.task_type" placeholder="请选择任务类型">
            <el-option label="升级任务" value="upgrade" />
            <el-option label="配置任务" value="config" />
          </el-select>
        </el-form-item>
        <el-form-item label="目标版本" prop="version">
          <el-select v-model="taskForm.version" placeholder="请选择目标版本">
            <el-option 
              v-for="firmware in firmwares" 
              :key="firmware.version" 
              :label="firmware.version" 
              :value="firmware.version" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="设备SN" prop="sn">
          <el-input v-model="taskForm.sn" placeholder="留空表示所有设备" />
        </el-form-item>
        <el-form-item label="生效时间" prop="effective_time">
          <el-date-picker
            v-model="taskForm.effective_time"
            type="datetime"
            placeholder="选择生效时间"
          />
        </el-form-item>
        <el-form-item label="执行时间段" prop="execute_time">
          <el-input v-model="taskForm.execute_time" placeholder="如: 02:00-04:00" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showTaskDialog = false">取消</el-button>
          <el-button type="primary" @click="createTask" :loading="creatingTask">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 新增设备对话框 -->
    <el-dialog v-model="showDeviceDialog" title="新增设备" width="500px">
      <el-form :model="deviceForm" :rules="deviceRules" ref="deviceFormRef" label-width="120px">
        <el-form-item label="设备SN" prop="sn">
          <el-input v-model="deviceForm.sn" placeholder="请输入设备SN" />
        </el-form-item>
        <el-form-item label="当前版本" prop="current_version">
          <el-input v-model="deviceForm.current_version" placeholder="请输入当前版本" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showDeviceDialog = false">取消</el-button>
          <el-button type="primary" @click="createDevice" :loading="creatingDevice">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, SwitchButton } from '@element-plus/icons-vue'
import { productService, type Product } from '@/services/productService'
import { firmwareService, type Firmware, type CreateFirmwareRequest } from '@/services/firmwareService'
import { taskService, type Task, type CreateTaskRequest } from '@/services/taskService'
import { deviceService, type Device, type CreateDeviceRequest } from '@/services/deviceService'
import { upgradeService, type UpgradeRecord } from '@/services/upgradeService'
import { authService } from '@/services/authService'

const route = useRoute()
const router = useRouter()
const productId = computed(() => route.params.id as string)

// 用户信息
const userInfo = ref(authService.getUserInfo())

// 响应式数据
const product = ref<Product | null>(null)
const activeTab = ref('firmware')

// 监听tab切换
watch(activeTab, (newTab) => {
  if (newTab === 'upgrade') {
    loadUpgradeRecords()
  } else if (newTab === 'task') {
    loadTasks()
  } else if (newTab === 'device') {
    loadDevices()
  }
})

// 固件相关
const firmwares = ref<Firmware[]>([])
const firmwareLoading = ref(false)
const showFirmwareDialog = ref(false)
const creatingFirmware = ref(false)
const firmwareForm = ref<CreateFirmwareRequest>({
  version: '',
  product_id: productId.value,
  description: '',
  file: null as File | null
})
const firmwareRules = {
  version: [{ required: true, message: '请输入版本号', trigger: 'blur' }],
  file: [{ required: true, message: '请选择固件文件', trigger: 'change' }]
}
const fileList = ref([])
const uploadRef = ref()

// 任务相关
const tasks = ref<Task[]>([])
const taskLoading = ref(false)
const showTaskDialog = ref(false)
const creatingTask = ref(false)
const taskForm = ref<CreateTaskRequest>({
  name: '',
  effective_time: '',
  task_type: '',
  product_id: productId.value,
  version: '',
  execute_time: ''
})
const taskRules = {
  name: [{ required: true, message: '请输入任务名称', trigger: 'blur' }],
  task_type: [{ required: true, message: '请选择任务类型', trigger: 'change' }],
  version: [{ required: true, message: '请选择目标版本', trigger: 'change' }],
  effective_time: [{ required: true, message: '请选择生效时间', trigger: 'change' }]
}

// 设备相关
const devices = ref<Device[]>([])
const deviceLoading = ref(false)
const showDeviceDialog = ref(false)
const creatingDevice = ref(false)
const deviceForm = ref<CreateDeviceRequest>({
  sn: '',
  product_id: productId.value,
  current_version: ''
})
const deviceRules = {
  sn: [{ required: true, message: '请输入设备SN', trigger: 'blur' }]
}

// 升级记录相关
const upgradeRecords = ref<UpgradeRecord[]>([])
const upgradeLoading = ref(false)

// 表单引用
const firmwareFormRef = ref()
const taskFormRef = ref()
const deviceFormRef = ref()

// 加载产品信息
const loadProduct = async () => {
  try {
    product.value = await productService.getProduct(productId.value)
  } catch (error) {
    ElMessage.error('获取产品信息失败')
  }
}

// 加载固件列表
const loadFirmwares = async () => {
  firmwareLoading.value = true
  try {
    firmwares.value = await firmwareService.getFirmwares(productId.value)
  } catch (error) {
    ElMessage.error('获取固件列表失败')
  } finally {
    firmwareLoading.value = false
  }
}

// 加载任务列表
const loadTasks = async () => {
  taskLoading.value = true
  try {
    tasks.value = await taskService.getTasks(productId.value)
  } catch (error) {
    ElMessage.error('获取任务列表失败')
  } finally {
    taskLoading.value = false
  }
}

// 加载设备列表
const loadDevices = async () => {
  deviceLoading.value = true
  try {
    devices.value = await deviceService.getDevices(productId.value)
  } catch (error) {
    ElMessage.error('获取设备列表失败')
  } finally {
    deviceLoading.value = false
  }
}

// 加载升级记录
const loadUpgradeRecords = async () => {
  upgradeLoading.value = true
  try {
    upgradeRecords.value = await upgradeService.getUpgradeRecords(productId.value)
  } catch (error) {
    ElMessage.error('获取升级记录失败')
  } finally {
    upgradeLoading.value = false
  }
}

// 文件上传处理
const handleFileChange = (file: any) => {
  firmwareForm.value.file = file.raw
}

// 创建固件
const createFirmware = async () => {
  if (!firmwareFormRef.value) return
  
  await firmwareFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      creatingFirmware.value = true
      try {
        await firmwareService.createFirmware(firmwareForm.value)
        ElMessage.success('固件创建成功')
        showFirmwareDialog.value = false
        firmwareForm.value = { version: '', product_id: productId.value, description: '', file: null as File | null }
        fileList.value = []
        loadFirmwares()
      } catch (error) {
        ElMessage.error('固件创建失败')
      } finally {
        creatingFirmware.value = false
      }
    }
  })
}

// 创建任务
const createTask = async () => {
  if (!taskFormRef.value) return
  
  await taskFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      creatingTask.value = true
      try {
        await taskService.createTask(taskForm.value)
        ElMessage.success('任务创建成功')
        showTaskDialog.value = false
        taskForm.value = { name: '', effective_time: '', task_type: '', product_id: productId.value, version: '', execute_time: '' }
        loadTasks()
      } catch (error) {
        ElMessage.error('任务创建失败')
      } finally {
        creatingTask.value = false
      }
    }
  })
}

// 创建设备
const createDevice = async () => {
  if (!deviceFormRef.value) return
  
  await deviceFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      creatingDevice.value = true
      try {
        await deviceService.createDevice(deviceForm.value)
        ElMessage.success('设备创建成功')
        showDeviceDialog.value = false
        deviceForm.value = { sn: '', product_id: productId.value, current_version: '' }
        loadDevices()
      } catch (error) {
        ElMessage.error('设备创建失败')
      } finally {
        creatingDevice.value = false
      }
    }
  })
}

// 下载固件
const downloadFirmware = (firmware: Firmware) => {
  const filename = firmware.download_url.split('/').pop()
  if (filename) {
    window.open(firmwareService.downloadFirmware(filename), '_blank')
  }
}

// 删除固件
const deleteFirmware = async (firmware: Firmware) => {
  try {
    await ElMessageBox.confirm(`确定要删除固件 "${firmware.version}" 吗？`, '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await firmwareService.deleteFirmware(firmware.id)
    ElMessage.success('固件删除成功')
    loadFirmwares()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('固件删除失败')
    }
  }
}

// 编辑任务
const editTask = (task: Task) => {
  ElMessage.info(`编辑任务: ${task.name}`)
}

// 删除任务
const deleteTask = async (task: Task) => {
  try {
    await ElMessageBox.confirm(`确定要删除任务 "${task.name}" 吗？`, '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await taskService.deleteTask(task.id)
    ElMessage.success('任务删除成功')
    loadTasks()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('任务删除失败')
    }
  }
}

// 编辑设备
const editDevice = (device: Device) => {
  ElMessage.info(`编辑设备: ${device.sn}`)
}

// 删除设备
const deleteDevice = async (device: Device) => {
  try {
    await ElMessageBox.confirm(`确定要删除设备 "${device.sn}" 吗？`, '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await deviceService.deleteDevice(device.id)
    ElMessage.success('设备删除成功')
    loadDevices()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('设备删除失败')
    }
  }
}

// 获取状态类型
const getStatusType = (status: string) => {
  switch (status) {
    case 'pending': return 'warning'
    case 'running': return 'primary'
    case 'completed': return 'success'
    case 'failed': return 'danger'
    default: return 'info'
  }
}

// 获取升级状态类型
const getUpgradeStatusType = (status: string) => {
  switch (status) {
    case 'success': return 'success'
    case 'failed': return 'danger'
    case 'in_progress': return 'primary'
    default: return 'info'
  }
}

// 格式化日期
const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleString()
}

// 格式化文件大小
const formatFileSize = (bytes: number) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 组件挂载时加载数据
onMounted(() => {
  loadProduct()
  loadFirmwares()
  loadTasks()
  loadDevices()
  loadUpgradeRecords()
})

// 登出功能
const handleLogout = () => {
  authService.logout()
  router.push('/login')
}
</script>

<style scoped>
.product-detail {
  height: 100vh;
  width: 100%;
  overflow-x: hidden;
}

.full-height {
  height: 100%;
}

.full-height-tabs {
  height: 100%;
}

.full-height-tabs :deep(.el-tabs__content) {
  height: calc(100% - 40px);
  overflow-y: auto;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  max-width: 1200px;
  padding: 0 20px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 20px;
}

.header-left h1 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.username {
  color: #666;
  font-size: 14px;
}

.header {
  background-color: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 50px;
  flex-shrink: 0;
}

.main-content {
  padding: 10px;
  height: calc(100vh - 50px);
  overflow: hidden;
}

.tab-content {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.tab-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  flex-shrink: 0;
}

.tab-content :deep(.el-table) {
  flex: 1;
  overflow: auto;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.content-card {
  margin: 0;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.06);
  border-radius: 8px;
}

.content-card :deep(.el-card__body) {
  padding: 10px;
}
</style> 